<template>
  <div>
    <el-container style="height: 100vh">
      <!-- 左侧列表 el-aside -->
      <el-aside class="el-menu" style="width: 180px; background-color: rgb(238, 241, 246);height: 100%">
        <el-menu :default-openeds="['1', '3']" default-active="2" class="el-menu-vertical-demo"
          style="min-height: 100%; overflow-x:hidden" background-color="rgb(48,65,86)" text-color="#fff"
          active-text-color="#ffd04b" :collapse-transition="false" router :default-active="this.$route.path">
          <div style="height: 40px; line-height: 40px; text-align: center">
            <img src="../assets/logo.png" alt=""
              style="width: 20px; height: 20px; position: relative; top: 5px; margin-right: 4px">
            <b style="color: white">智慧教培管理系统</b>
          </div>

          <el-submenu index="1">
            <template slot="title"><i class="el-icon-document"></i>
              <span slot="title">学生信息</span>
            </template>
            <el-menu-item @click="queryStudents" :default-active="$route.path">查询学生信息</el-menu-item>
          </el-submenu>

          <el-submenu index="3">
            <template slot="title"><i class="el-icon-document"></i>
              <span slot="title">导入导出</span>
            </template>
            <el-menu-item type="primary" @click="downloadStudents" :default-active="$route.path">导出学生信息</el-menu-item>
          </el-submenu>

        </el-menu>

      </el-aside><!-- el-aside 左侧列表到此结束-->

      <el-container><!-- 中间查询学生信息-->
        <el-main>
          <div>
            <el-breadcrumb separator-class="el-icon-arrow-right">
              <el-breadcrumb-item :to="{ path: '/' }">返回首页</el-breadcrumb-item>
              <el-breadcrumb-item>学生信息</el-breadcrumb-item>
            </el-breadcrumb>
          </div>

          <div>

            <div class="toolbar right">
              <el-row>
                <el-col :span="18">
                  <el-input v-model="qname" placeholder="请输入姓名" clearable @clear="getStudentsList">

                    <el-button type="primary" slot="append" icon="el-icon-search" @click="getStudentsList"></el-button>
                  </el-input>
                </el-col>
              </el-row>
            </div>

            <el-table empty-text="请点击查询，查询数据" :data="students" v-loading="loading"
              :header-cell-style="{ 'text-align': 'center' }" :cell-style="{ 'text-align': 'center' }">
              <el-table-column prop="sid" label="学号" width="80"></el-table-column>
              <el-table-column prop="sname" label="姓名" width="100"></el-table-column>
              <el-table-column prop="sage" label="年龄" width="100"></el-table-column>
              <el-table-column prop="ssex" label="性别" width="100"></el-table-column>
              <el-table-column prop="className" label="所属班级" width="100"></el-table-column>

              <el-table-column label="操作">
                <template slot-scope="scope">
                  <el-button type="primary" size="mini" icon="el-icon-edit" @click="handleEdit(scope.row)">编辑</el-button>
                  <el-button type="danger" size="mini" icon="el-icon-delete"
                    @click="deleteStudent(scope.row)">删除</el-button>
                  <el-button type="primary" size="mini" icon="el-icon-plus" @click="dialogVisible = true">添加</el-button>
                </template>
              </el-table-column>
            </el-table>

            <div class="pagination-container">
              <el-pagination @size-change="changePageSize" @current-change="changePage" :current-page="currentPage"
                :page-sizes="[5, 10, 20, 500]" :page-size="pageSize" layout="total, sizes, prev, pager, next, jumper"
                :total="total">
              </el-pagination>
            </div>
          </div>

          <!-- 添加学生对话框 -->
          <el-dialog :visible="dialogVisible">
            <AddStudent v-bind:dialogVisible="dialogVisible" @closeDialog="closeDialog" />
          </el-dialog>

          <!-- 编辑框 -->
          <el-dialog title="编辑学生" :visible.sync="dialogFormVisible">
            <el-form :model="editStudent">
              <el-form-item label="姓名">
                <el-input v-model="editStudent.sname" style="width: 70%"></el-input>
              </el-form-item>
              <el-form-item label="年龄">
                <el-input v-model="editStudent.sage" style="width: 70%"></el-input>
              </el-form-item>
              <el-form-item label="性别">
                <el-input v-model="editStudent.ssex" style="width: 70%"></el-input>
              </el-form-item>
              <el-form-item label="所属班级" prop="classId">
                <el-select v-model="editStudent.classId" placeholder="请选择班级">
                  <el-option v-for="item in classList" :key="item.classId" :label="item.className" :value="item.classId">
                  </el-option>
                </el-select>
              </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer">
              <el-button @click="dialogFormVisible = false">取消</el-button>
              <el-button type="primary" @click="handleEditStudent">确定</el-button>
            </div>
          </el-dialog>
        </el-main>
      </el-container>
    </el-container>
  </div>
</template>
<script>

import AddStudent from './AddStudent.vue'; // 引入添加学生子组件

export default {
  name: 'StudentView', // 父组件的名称
  components: {
    AddStudent // 注册子组件
  },
  data() {
    return {

      qname: '',
      total: 0,
      editStudent: {
        sname: "",
        sage: 0,
        ssex: "",
        classId: ""
      },
      classList: [
      
      ],
      students: [],
      totalPages: 0,
      currentPage: 1,
      pageSize: 5,
      loading: false,
      dialogVisible: false,// 控制添加学生对话框的显示/隐藏
      dialogFormVisible: false,// 控制编辑学生对话框的显示/隐藏
      searchText: "",
    }
  },
  created() {
    this.queryStudents();

  },
  computed: {
    showPagination() {
      return this.totalPages > 1
    },
    // 定义一个计算属性classText，通过遍历 classList 数组来查找 classId 等于 editStudent.classId 的项，然后返回对应的 className。
    // 在模板中，将 editStudent.classId 绑定到 v-model 中，同时在另一个元素中绑定计算属性 classText 来显示对应的文字。

  },
  methods: {
    async closeDialog(isAdd) {
      this.dialogVisible = false
      if (isAdd == true) {
        if (this.total % this.pageSize == 0) {
          this.currentPage = this.currentPage + 1;
        }
        this.queryStudents();
      }
    },
    async selectPageSize() {
      this.queryStudents();
    },
    async changePageSize(size) {
      this.pageSize = size;
      this.queryStudents()
    },
    async queryStudents() {
      this.loading = true;
      try {
        const response = await this.$axios({
          url: '/getStudents',
          params: {
            page: this.currentPage,
            pageSize: this.pageSize,

          }
        })
        const { data, totalPages, total } = response.data;
        this.total = total;
        this.students = data;
        this.totalPages = totalPages;

      } catch (error) {
        console.log(error);
      } finally {
        this.loading = false;
      }
    },
    async downloadStudents() {
      try {
        const response = await this.$axios.get('/download', { responseType: 'blob' });
        const url = window.URL.createObjectURL(new Blob([response.data]));
        const link = document.createElement('a');
        link.href = url;
        link.setAttribute('download', '学生信息表.xlsx');
        document.body.appendChild(link);
        link.click();
      } catch (error) {
        console.log(error);
      }
    },
    async changePage(currentPage) {
      this.currentPage = currentPage;
      await this.queryStudents();
    },
    async deleteStudent(student) {
      try {
        await this.$confirm(`确认删除学号为 ${student.sid} 的学生信息吗？`, '删除学生信息', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        });
        await this.$axios.delete(`/deleteStudent/${student.sid}`);
        this.$message.success('删除成功');
        if (this.total % this.pageSize == 1) {
          this.currentPage = this.currentPage - 1;
        }
        this.queryStudents();
      } catch (error) {
        console.log(error);
        this.$message.error('删除失败');
        this.queryStudents();
      }
    },
    //编辑
    handleEdit(row) {
      this.dialogFormVisible = true;
      Object.assign(this.editStudent, row); // 克隆当前行数据
      this.$axios.get(`/sClass`).then(response => {
        const { code, message } = response.data;
        this.classList = response.data.data
        if (code != "200") {
          this.$message.error(message);
        } 
      }).catch(error => {
        console.log(error);
        // this.$message.error('修改失败');
      });
    },
    //提交编辑
    handleEditStudent() {
      this.$axios.put(`/editStudent`, {
        sid: this.editStudent.sid,
        sname: this.editStudent.sname,
        sage: this.editStudent.sage,
        ssex: this.editStudent.ssex,
        classId: this.editStudent.classId,
      }).then(response => {
        const { code, message } = response.data;
        if (code === "200") {
          this.dialogFormVisible = false;// 隐藏编辑页面
          this.$message({
            message: "修改成功",
            type: 'success'
          });
          this.queryStudents();
        } else {
          this.$message.error(message);
        }
      }).catch(error => {
        console.log(error);
        // this.$message.error('修改失败');
      });
    },
    async getStudentsList() {
      const response = await this.$axios({
        url: '/getStudentsList',
        params: {
          page: this.currentPage - 1,
          pageSize: this.pageSize,
          name: this.qname
        }
      })
      const { data, totalPages, total } = response.data;
      this.total = total;
      this.students = data
      this.totalPages = totalPages;

      if (response.status === 200 && response.data.code === 200)
        return this.$message.error(response.msg)
      this.$message({
        message: "查询成功",
        type: 'success'
      })
    }
  }
}
</script>
<style src="@/style/student.css"></style> 
